package com.nxmu.hire.service.impl;

import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.dao.GradeCoefficientMapper;
import com.nxmu.hire.model.GradeCoefficient;
import com.nxmu.hire.model.GradeCoefficientExample;
import com.nxmu.hire.model.enums.SemesterEnum;
import com.nxmu.hire.service.GradeCoefficientService;
import com.nxmu.hire.utils.HireUtil;
import com.nxmu.hire.vo.GradeCoefficientReqVo;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class GradeCoefficientServiceImpl implements GradeCoefficientService {

    private final static Logger LOGGER = LoggerFactory.getLogger(GradeCoefficientServiceImpl.class);

    @Autowired
    private GradeCoefficientMapper gradeCoefficientMapper;

    /**
     * 查找最新的评分系数
     * @return
     */
    @Override
    public GradeCoefficient findLastGradeCoefficient() {
        // 当前数据库中目前只保留一条数据，所以直接取查询出来的一第一条记录
        List<GradeCoefficient> gradeCoefficients = gradeCoefficientMapper.selectByExample(new GradeCoefficientExample());
        return gradeCoefficients == null || gradeCoefficients.isEmpty() ? null : gradeCoefficientMapper.selectByExample(new GradeCoefficientExample()).get(gradeCoefficients.size() - 1);
    }

    /**
     * 添加标准系数
     *
     * @param gradeCoefficientReqVo
     */
    @Transactional
    @Override
    public void save(GradeCoefficientReqVo gradeCoefficientReqVo) throws ServiceException {
        GradeCoefficient gradeCoefficient = new GradeCoefficient();
        BeanUtils.copyProperties(gradeCoefficientReqVo,gradeCoefficient);
        gradeCoefficient.setSchoolYear(HireUtil.countSchoolYear(LocalDate.now()));
        gradeCoefficient.setSemester(HireUtil.countSemester(LocalDate.now()));
        try {
            gradeCoefficientMapper.insert(gradeCoefficient);
        } catch (Exception e) {
            LOGGER.error("添加标准系数失败");
            throw new ServiceException("添加标准系数失败");
        }
    }

    /**
     * 根据学年和学期查询评分系数
     * @return
     */
    @Override
    public GradeCoefficient findByYearAndSemester(Integer schoolYear, SemesterEnum semester) throws ServiceException {
        GradeCoefficientExample gradeCoefficientExample = new GradeCoefficientExample();
        gradeCoefficientExample.createCriteria()
                .andSchoolYearEqualTo(schoolYear)
                .andSemesterEqualTo(semester);
        List<GradeCoefficient> gradeCoefficients = gradeCoefficientMapper.selectByExample(gradeCoefficientExample);
        if (gradeCoefficients != null && gradeCoefficients.size() > 1) throw new ServiceException("评分系数异常");
        return gradeCoefficients.get(0);
    }
}
